package utils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: NGUYEN VAN NHAN
 * Date: 9/17/14
 * Time: 2:36 PM
 * Long Van Soft Solution Sjc.
 * To change this template use File | Settings | File Templates.
 */
public abstract class BaseManager {
    private Logger logger = null;
    @PersistenceContext(name = "Product")
    private EntityManager entityManager;

    protected EntityManager getEntityManager() {
        return entityManager;
    }

    protected void create(Object paramObject) {
        this.entityManager.persist(paramObject);
    }

    protected <T> T edit(T paramT) {
        return this.entityManager.merge(paramT);
    }

    protected void remove(Object paramObject) {
        this.entityManager.remove(paramObject);
    }

    protected <T> T find(Class<T> entityClass, Object primaryKey) {
        return this.entityManager.find(entityClass, primaryKey);
    }


    protected <T> List<T> findAll(Class<T> entityClass) {
        CriteriaQuery cq = this.entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return this.entityManager.createQuery(cq).getResultList();
    }

    public abstract String getClassName();

    public Logger getLogger() {
        if (null == logger) {
            logger = Logger.getLogger(getClassName());
        }
        return logger;
    }

    public void logError(String message, Exception exception) {
        getLogger().log(Level.WARNING, message, exception);
    }
}
